package com.example.product.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.product.VO.ProductInfoVO;
import com.example.product.VO.ProductVO;
import com.example.product.VO.ResultVO;
import com.example.product.dataobject.ProductCategory;
import com.example.product.dataobject.ProductInfo;
import com.example.product.service.CategoryService;
import com.example.product.service.ProductService;
import com.example.product.utils.ResultVOUtil;

@RestController
@RequestMapping("/product")
public class ProductController {

	@Autowired
	private ProductService productService;

	@Autowired
	private CategoryService categoryService;

	@GetMapping("/list")
	public ResultVO<List<ProductVO<ProductInfoVO>>> list() {
		List<ProductInfo> productInfoList = productService.findUpAll();
		List<Integer> categoryTypeList = productInfoList
				.stream()
				.map(ProductInfo::getCategoryType)
				.collect(Collectors.toList());
		List<ProductCategory> categoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
		List<ProductVO<ProductInfoVO>> productVOList = new ArrayList<>();

		for (ProductCategory productCategory : categoryList) {
			ProductVO<ProductInfoVO> vo = new ProductVO<>();
			vo.setCategoryName(productCategory.getCategoryName());
			vo.setCategoryType(productCategory.getCategoryType());

			List<ProductInfoVO> productInfoVOList = new ArrayList<>();
			for (ProductInfo info : productInfoList) {
				if (info.getCategoryType().equals(productCategory.getCategoryType())) {
					ProductInfoVO productInfoVO = new ProductInfoVO();
					BeanUtils.copyProperties(info, productInfoVO);
					productInfoVOList.add(productInfoVO);
				}
			}
			vo.setProductInfoVOList(productInfoVOList);

			productVOList.add(vo);
		}
		
		
		return ResultVOUtil.success(productVOList);
	}
}
